import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';
import PrintEncrypt from '../factory/print_encrypt';
import Transfer from './transfer';
class StoreItem extends Model { }

StoreItem.init({
    name: DataTypes.STRING,
    UserId: DataTypes.INTEGER,
    TemplateId: DataTypes.INTEGER,
    price: DataTypes.INTEGER,
    dis: DataTypes.STRING,
    isSaled: {
        type: DataTypes.BOOLEAN,
        defaultValue: false
    }
}, {
    sequelize,
    hooks: {
        afterBulkCreate: (store, options) => {
            Transfer.bulkCreate(store.map((item) => ({ step: 1, UserId: item.dataValues.UserId, StoreItemId: item.dataValues.id })))
            PrintEncrypt.bulkCreate(store.map((item) => ({ StoreItemId: item.dataValues.id, code: Math.floor(Math.random() * 100000) })))
        },
        afterUpdate: async (store, options) => {
            const { UserId, id } = store.dataValues
            if (options.fields?.includes('UserId') && UserId) {
                const transfer = await Transfer.findOne({ where: { StoreItemId: id }, order: [['step', 'DESC']] })
                if (!transfer) return
                const { dataValues } = transfer
                await Transfer.create({
                    step: dataValues.step + 1, UserId: UserId, StoreItemId: id, from: dataValues.UserId
                })
            }
        }
    }
});

export default StoreItem